package com.arrake.utils;

import org.dom4j.Document;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class DocxReader {
    public static Document[] readerXmlDocRes(String filePath) throws Exception {
        Matcher matcher = Pattern.compile(".docx").matcher(filePath);
        if (!matcher.find()) {
            throw new Exception("该文件不是docx文件");
        }
        Document doc = null;
        Document res = null;
        //获得输入流，文件为zip格式，
        //zip可以包含对个文件，如果只有一个文件，则只解析一个文件的，包含多个文件则分别解析
        ZipInputStream in = new ZipInputStream(new FileInputStream(filePath));
        //不解压直接读取,加上gbk解决乱码问题
        String docXml = "";
        String resXml = "";
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
        ZipEntry zipFile;
//        判断该文件是否符合docx规范
        if (in.getNextEntry() == null)
            throw new Exception("这个是假的docx文件");
//        in.reset();


        //循环读取zip中的cvs/txt文件，zip文件名不能包含中文
        while ((zipFile = in.getNextEntry()) != null) {
            //获得cvs名字
            String fileName = zipFile.getName();
            //检测文件是否存在
            if (fileName.equals("word/document.xml")) {
                String line;
                while ((line = br.readLine()) != null) {
                    docXml = docXml + line + "\n";
                }
            } else if (fileName.equals("word/_rels/document.xml.rels")) {
                String line;
                while ((line = br.readLine()) != null) {
                    resXml = resXml + line + "\n";
                }
            }
        }
        //关闭流
        br.close();
        in.close();


        Reader docReader = new StringReader(docXml);
        StringReader resReader = new StringReader(resXml);
        SAXReader reader = new SAXReader();
        doc = reader.read(docReader);
        res = reader.read(resReader);
        Document[] documents = {doc, res};
        return documents;
    }

    public static String zipPictureCopy(String pathPicture, String filePath) throws Exception {


        String dir = "src\\main\\resources\\docxTemplate\\word\\media";
        String fileName = null;
        String sufFileName = null;

//        获取文件名后缀
        Matcher matcher = Pattern.compile("\\..*").matcher(pathPicture);
        matcher.find();
        sufFileName = matcher.group();

//        遍历文件获取文件名
        File file = new File(dir);
        File[] files = file.listFiles();
        for (File file1 : files) {
//           找到最大数字文件名哪个
            if (fileName == null) {
                fileName = file1.getName();
            } else {
                String[] split1 = file1.getName().split("\\.");
                String num1 = split1[0].substring(5);
                String[] split2 = fileName.split("\\.");
                String num2 = split2[0].substring(5);
                if (Integer.parseInt(num1) > Integer.parseInt(num2)) {
                    fileName = file1.getName();
                }
            }

        }
//        将最大数字文件名的文件+1
        if (fileName == null) {
            fileName = "image1" + sufFileName;
        } else {
            String[] split = fileName.split("\\.");
            String num = split[0].substring(5);
            fileName = "image" + (Integer.parseInt(num) + 1) + sufFileName;
        }

        ZipInputStream in = new ZipInputStream(new FileInputStream(filePath));
        ZipEntry zipFile;
        //循环读取zip中的cvs/txt文件，zip文件名不能包含中文
        while ((zipFile = in.getNextEntry()) != null) {
            //获得cvs名字
            String fileName1 = zipFile.getName();
            //检测文件是否存在
            if (fileName1.equals("word/" + pathPicture)) {
                //文件复制
                OutputStream out = new FileOutputStream(new File(dir + "//" + fileName));
                byte[] buffer = new byte[1024];
                int len;

                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                out.close();
            }

        }
        in.close();
        return fileName;
    }

    public static Document readerNumbering(String filePath) throws Exception {
        ZipInputStream in = new ZipInputStream(new FileInputStream(filePath));
        String numberingXml = "";
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
        ZipEntry zipFile;

        while ((zipFile = in.getNextEntry()) != null) {
            //获得cvs名字
            String fileName = zipFile.getName();
            //检测文件是否存在
            if (fileName.equals("word/numbering.xml")) {
                String line;
                while ((line = br.readLine()) != null) {
                    numberingXml = numberingXml + line + "\n";
                }
            }
        }
        //关闭流
        br.close();
        in.close();
        if (numberingXml.equals("")){
            return  null;
        }

        Reader numberingReader = new StringReader(numberingXml);
        SAXReader reader = new SAXReader();
        return reader.read(numberingReader);
    }
}
